#pragma once
#include<iostream>
#include<string>
#include<functional>
#include<pthread.h>

namespace ThreadModule
{
    using func_t = std::function<void(const std::string&)>;
    class Thread
    {   
        //typedef void(*func_t)(ThreadData* td); 
        
    public:
        void Excute()
        {
            //std::cout << _name << " is running" << std::endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
    public:
        Thread(const std::string& name,func_t func):_name(name),_func(func)
        {
            //std::cout << "create " << name << " done" << std::endl;
        }
        static void* ThreadRoutine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);//获得了当前对象
            self->Excute();
            return nullptr;
        }
        std::string Status()
        {
            if(_isrunning) return "running";
            else return "sleep";
        }
        bool Start()
        {
            //::表示使用库中的调用
            int n = ::pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n != 0) return false;
            return true;
        }
        std::string& Name()
        {
            return _name;
        }
        void Stop() 
        {
            if(_isrunning)
            {
                _isrunning = false;
                ::pthread_cancel(_tid);
                //std::cout << _name << " Stop" << std::endl;
            }
        }
        void Join()
        {
            ::pthread_join(_tid,nullptr); 
            //std::cout << _name << " Joined" << std::endl;
        }
        ~Thread()
        {
        }
    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;//线程要执行的回调函数
    };
}